// 所有的数据操作都由 Redux Toolkit 来完成
import { createSlice, createAsyncThunk } from "@reduxjs/toolkit"
import { categoriesAPI } from "../../api"

// 异步获取全部商品

export const fetchCategories = createAsyncThunk(
    'categories/fetchCategories',
    async () => {
        const response = await categoriesAPI.getAll()
        // 返回的数据会作为 action.payload
        return response.data
    },
)


// 定义初始状态
const initialState = {
    categories: [],
    // 选中的分类
    selectedCategoryId: 1,
    // 错误信息
    error: null,
    // 加载状态（有异步） 不需要设置，因为使用的是 createAsyncThunk 的 pending, fulfilled, rejected
    loading: false,
}

// 生成 product的 reducer 和 actions
const categoriesSlice = createSlice({
    name: "categories",
    initialState,
    reducers: {
        selectCategory(state, action) {
            state.selectedCategoryId = action.payload
        }
    },
    // 异步的 处理逻辑
    extraReducers: (builder) => {
        builder
            .addCase(fetchCategories.pending, (state) => {
                state.loading = true
            })
            .addCase(fetchCategories.fulfilled, (state, action) => {
                state.loading = false
                state.categories = action.payload
            })
            .addCase(fetchCategories.rejected, (state, action) => {
                state.loading = false
                state.error = action.error.message
            })
    }

})
export const { selectCategory } = categoriesSlice.actions
export default categoriesSlice.reducer